from django.shortcuts import render, redirect
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from django_redis import get_redis_connection
from rest_framework.viewsets import ModelViewSet
from apps.users.models import User
from rest_framework.response import Response

from ten_times import settings
from utils.smscodes import send_message
from rest_framework import status
from . import serializer
from utils.fdfs.fastdfs_storage import FastDFSStorage
from apps.question.models import Label
# TODO 短信验证码 :接收用户手机,给用户手机发送短信验证码
class SmsCodesAPIView(APIView):
    """
    获取短信验证码
    GET

    思路:
    创建序列化器,定义text 和 image_code_id
    redis 判断该用户是否频繁获取
    生成短信验证码
    redis增加记录
    发送短信
    返回响应
    """
    def get(self,request,mobile):
        from random import randint
        sms_code = "%06d" % randint(0, 999999)
        # sms_code = randint(100000, 999999)
        print(sms_code)
        sms_redis_client = get_redis_connection('sms_code')

        # 1.取出标识
        send_flag = sms_redis_client.get('send_flag_%s' % mobile)
        # 2.判断标识
        if send_flag:
            return Response('短信发送频繁')

        # 1.实例化管道
        pipeline = sms_redis_client.pipeline()
        # 2.将任务添加管道
        pipeline.setex('send_flag_%s' % mobile, 60, 1)
        pipeline.setex("sms_%s" % mobile, 300, sms_code)
        # 3.实行管道'
        pipeline.execute()
        # 4.让第三方 容联云-给手机号-发送短信
        # 4.云通讯发送
        # send_message(mobile,sms_code)
        # delay 的参数 同 send_message 的参数
        # TODO 暂时不用这个功能
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)
        # 6.返回响应
        return Response({'success':True,'sms_code':sms_code,'message':'OK'})
# 用户注册
class CreateUserView(CreateAPIView):
    serializer_class = serializer.CreateUserSerializer
# 上传图片
class ImageUploadViewForAvatar(APIView):
    def post(self, request):
        storage = FastDFSStorage()
        ret = storage._save("", request.data.get("img"))
        ret_url = settings.FDFS_URL + ret
        return Response({"imgurl": ret_url})
# 富文本上传
class ImageUploadViewForCKEditor(APIView):
    def post(self, request):
        storage = FastDFSStorage()
        ret = storage._save("", request.data.get("upload"))
        from_address = request.META['HTTP_REFERER']
        from_address = from_address[:from_address.rfind('/'):]
        ret_url = from_address + '/upload_success.html?image_url=' + settings.FDFS_URL + ret + '&CKEditorFuncNum=' + request.query_params.get(
            'CKEditorFuncNum')
        return redirect(ret_url)
# 擅长技能
class UserlableAPIView(APIView):
    def put(self,request):
        user = request.user
        labels_set = request.data.get('labels')
        user.labels.set(labels_set)
        return Response({'success':True})
